package system_services

import (
	"go_ruoyi/global"
	"go_ruoyi/model/db_model"
	"go_ruoyi/model/response_model"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 树形部门
type TreeDeptStruct struct {
	Id       int64             `json:"id"`
	Pid      int64             `json:"-"`
	Label    string            `json:"label"`
	Children []*TreeDeptStruct `json:"children"`
}

func TreeDept(items []*db_model.Dept) []*TreeDeptStruct {

	var nodes []*TreeDeptStruct
	for _, item := range items {
		node := &TreeDeptStruct{
			Id:       item.DeptId,
			Pid:      item.ParentId,
			Label:    item.DeptName,
			Children: nil,
		}
		nodes = append(nodes, node)
	}

	treeLists := Tree(nodes, 0)
	return treeLists
}

func Tree(node []*TreeDeptStruct, pid int64) []*TreeDeptStruct {
	res := make([]*TreeDeptStruct, 0)
	for _, v := range node {
		if v.Pid == pid {
			v.Children = Tree(node, v.Id)
			res = append(res, v)
		}
	}
	return res
}

func GetTreeDept(c *gin.Context) {
	dept := make([]*db_model.Dept, 0)
	if err := global.DB.Find(&dept).Error; err != nil {
		response_model.FailWithMsg(c, "系统异常")

	}
	deptTree := TreeDept(dept)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"data":    deptTree,
		"message": "操作成功",
	})
}
